import { defineComponent, inject, ref, watchEffect, computed, onMounted, nextTick } from 'vue'
import { useTabsStore } from '@/stores/modules/tabs'
import { themesStore } from '@/stores/modules/theme'
import { storeToRefs } from 'pinia'
import { NCollapse, NCollapseItem } from 'naive-ui'
import { useRouter } from 'vue-router'
import pcStyle from './style/pc.module.scss'
import type { menuState } from '@/types/system'

export default defineComponent({
  setup() {
    const title = import.meta.env.VITE_GLOB_APP_TITLE
    const theme = themesStore()
    const tabsStore = useTabsStore()
    const { getNavTwoWidth } = storeToRefs(theme)
    const {
      getCurrenName: currentName,
      getOneMeun: meun,
      getChilderInfo: childerInfo,
      getLeavelOne: leavelOne,
    } = storeToRefs(tabsStore)

    const { setLeaverOne, setCurrenName } = tabsStore
    const router = useRouter()
    let isInitPage = false
    const getActiveTop = (cu: number) => {
      if (!isInitPage) return
      if (meun.value.length > 0) {
        nextTick(() => {
          const dome = document.getElementById(`menudome${cu}`)
          if (dome) {
            activeTop.value = dome.offsetTop + 'px'
          }
        })
      }
    }

    const activeTop = ref('')
    watchEffect(() => {
      getActiveTop(leavelOne.value)
    })

    const handJump = (row: menuState) => {
      router.push({
        name: row.name,
      })
    }

    const isOpen = inject('isOpen')
    const isOpenChange = inject('isOpenChange')
    const listWidht = computed(() => {
      if (leavelOne.value === -1) {
        return '0px'
      }
      const info = meun.value[leavelOne.value]
      if (!info) {
        return '0px'
      }
      if (!info.meta.showNext) {
        return '0px'
      }
      return isOpen.value ? getNavTwoWidth.value : '0px'
    })
    const getLastPageInfo = (pageInfo) => {
      if (pageInfo?.children && pageInfo.children.length > 0) {
        return getLastPageInfo(pageInfo.children[0])
      }
      return pageInfo
    }
    const handChange = (e: number) => {
      const pageInfo = setLeaverOne(e)
      if (!pageInfo) return
      const lastInfo = getLastPageInfo(pageInfo)
      setCurrenName(lastInfo.name)
      router.push({
        name: lastInfo.name,
      })
    }

    onMounted(() => {
      isInitPage = true
      if (!activeTop.value) {
        getActiveTop(leavelOne.value)
      }
    })
    return () => (
      <>
        <div class={` ${pcStyle.menu}`}>
          <div class="menu-left">
            <div class="menu-content">
              <div class="nav-title" onClick={isOpenChange}>
                <img src="https://vitejs.cn/logo.svg" alt="" />
              </div>
              <div class="scroll">
                <div class="list">
                  {meun.value.map((item, index: number) => (
                    <div
                      class={`item ${index === leavelOne.value ? 'item-active' : ''}`}
                      id={`menudome${index}`}
                      onClick={() => handChange(index)}
                    >
                      <i class={`esayIcon esayIcon-${item.meta.icon}`}></i>
                      <span class="name">{item.meta.title}</span>
                    </div>
                  ))}
                  {leavelOne.value >= 0 && (
                    <div class="menu-active" style={{ top: activeTop.value }}></div>
                  )}
                </div>
              </div>
            </div>
          </div>
          <div class="menu-list" style={{ width: listWidht.value }}>
            <div class="menu-list-main">
              <div class="nav-title">{title}</div>
              <div class="menu-list-maintwo">
                {childerInfo.value && (
                  <MenuList
                    current-name={currentName.value}
                    childer-router={childerInfo.value.children}
                    onChange={handJump}
                  />
                )}
              </div>
            </div>
          </div>
        </div>
      </>
    )
  },
})

const ChilderList = defineComponent({
  props: {
    currentName: {
      type: String,
      default: '',
    },
    collName: {
      type: String,
      default: '',
    },
    item: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  emits: ['change'],
  setup(props, { emit }) {
    const handClick = (e) => {
      emit('change', e)
    }
    return () => (
      <div class="menuList-item">
        <NCollapse
          class="w-full"
          accordion={true}
          default-expanded-names={props.collName}
          arrow-placement="right"
        >
          <NCollapseItem name={props.item.name}>
            {{
              header: () => (
                <div
                  class={`cell flex-1 ${
                    props.item.childrenNameList.includes(props.currentName)
                      ? 'cell-active-text'
                      : ''
                  }`}
                  style={{ paddingLeft: '20px' }}
                >
                  {props.item.icon && (
                    <span>
                      <i class={`esayIcon esayIcon-${props.item.icon}`}></i>
                    </span>
                  )}
                  <div class="metatitle u-line-1">{props.item.meta.title}</div>
                </div>
              ),
              default: () => (
                <div style={{ paddingLeft: '10px' }}>
                  <MenuList
                    childer-router={props.item.children}
                    current-name={props.currentName}
                    onChange={handClick}
                  />
                </div>
              ),
            }}
          </NCollapseItem>
        </NCollapse>
      </div>
    )
  },
})

const MenuList = defineComponent({
  props: {
    childerRouter: {
      type: Array,
      default: () => [],
    },
    currentName: {
      type: String,
      default: '',
    },
  },
  emits: ['change'],
  setup(props, { emit }) {
    const children = ref([])
    watchEffect(() => {
      if (props.childerRouter && props.childerRouter.length > 0) {
        children.value = props.childerRouter.filter((el) => {
          return !el.meta.isPage
        })
      }
    })

    const collName = computed(() => {
      const collInfo = props.childerRouter.find((el) =>
        el.childrenNameList.includes(props.currentName),
      )
      if (collInfo) {
        return collInfo.name
      }
      return ''
    })

    const handClick = (e) => {
      emit('change', e)
    }
    return () => (
      <>
        <div class={` ${pcStyle.menuList}`}>
          {children.value.map((item) =>
            item.children && item.children.length > 0 ? (
              <>
                <ChilderList
                  current-name={props.currentName}
                  coll-name={collName.value}
                  item={item}
                  onChange={handClick}
                />
              </>
            ) : (
              <div
                class={`cell ${item.name === props.currentName ? 'cell-active' : ''}`}
                onClick={() => handClick(item)}
              >
                {item.meta.icon && (
                  <span>
                    <i class={`esayIcon esayIcon-${item.icon}`}></i>
                  </span>
                )}
                <div class="metatitle u-line-1">{item.meta.title}</div>
              </div>
            ),
          )}
        </div>
      </>
    )
  },
})
